import getpath
import os
import re
import logging
import copy
import xml.etree.ElementTree
import myglobal
import openpyxl
from openpyxl.drawing.image import Image
from PyQt5 import QtWidgets
import io
from PIL import Image as PILImage

doc=None
filename=None
curvePage=-1
def elementWave(s):
    print(s)
    find=re.search(r"\d+(\.\d+)?[A-Z][a-z]*", s).group()
    wave=re.search(r"\d+(\.\d+)?", find).group()
    element=re.search(r"[A-Z][a-z]*", find).group()
    mode=s.split("(")[1].split(")")[0].strip().replace(" ","").replace("-","_")
    return(element,wave)#,True,mode)
def getdata_raw(filename1):
    global doc,filename
    filename=filename1
    doc = xml.etree.ElementTree.parse(filename)
    table=doc.find("Table")
    print(dir(table))
    # cs=table.getchildren()
    head=table.find("Header")
    rows=table.findall("Row")
    r=[]
    h=[]
    for one in head.findall("Cell"):
        h.append(one.text)
    r.append(h)
    for row in rows:
        h=[]
        for one in row.findall("Cell"):
            h.append(one.text)
        r.append(h)
    return r
def zl_data(data):
    start=4
    data_ele=data[0][start:]
    at=0
    items=[]
    concs=[]
    colidx=[]
    while(at<len(data_ele)):
        fs=data_ele[at].split(" ")
        r=elementWave(data_ele[at])
        items.append(r)
        colidx.append(at+start)
        at+=1
    items.append(("FinalQuantity",""))#,False,""))
    colidx.append(3)
    data=data[1:]
    r=[]
    for i in range(len(data)):
        sample={}
        # sample["items"]=copy.copy(items)
        row=data[i]
        id1=row[0]
        if id1=="":
            continue
        sample["sampleid"]=str(id1)
        sample["time"]=""
        if row[1]==None:
            sample["mass"]=""
            sample["volume"]=""
        else:
            mass=myglobal.myfloat(row[1])#(1/myglobal.myfloat(row[2]))/10.0
            sample["mass"]=str(mass)
            if mass>0.06:
                sample["volume"]="100"
            else:
                sample["volume"]="50"
        concs=[]
        for j in range(len(items)):
            v=row[colidx[j]]
            print(v)
            if v==None:
                concs.append("")
            else:
                arr=v.split(" ")
                if len(arr)==1:
                    concs.append(v)
                else:
                    if arr[1]=="%":
                        print("%")
                        if i==0: #first row
                            k=items[j]
                            items[j]=(k[0]+"内标",k[1])#,False,k[3])
                        concs.append(arr[0])
                    elif arr[1]=="ppb":
                        print("ppb")
                        concs.append(arr[0])
                    else:
                        concs.append(v)
        sample["conc"]=concs
        r.append(sample)
        # break
    return (items,r)
def outputImages(ts,ws,hang):#outputsheet,pdf filename,0-n page
    ss=QtWidgets.qApp.screens()
    if len(ss)<1:
        rowh=13.5/72.0*96
    else:
        rowh=13.5/72.0*ss[0].physicalDotsPerInch() #bang to pixel
    for i in range(len(ts)):
        (img,paras)=ts[i]
        folder=os.path.split(os.path.abspath(filename))[0]
        img = Image(os.path.join(folder,img))
        img.width=300#not too big
        img.height=200
        # print(dir(img))
        n=int((img.height)/rowh)
        at_row=i*n+hang
        for j in range(len(paras)):
            ws["A"+str(at_row+j)]=paras[j]
        ws.column_dimensions['A'].width = 30.0
        ws.add_image(img, "B"+str(at_row))  # 图片 插入 A1 的位置上    
def getimageTables():
    print(dir(doc))
    panel=doc.find("WrapPanel")
    print(panel,dir(panel))
    its=panel.find("Row").findall("Cell")
    print(its)
    r2=[]
    for one in its:
        table=one.find("LayoutTable")
        if table!=None:
            r=getImageTable_one(table)
            r2.append(r)
    return r2  
def getImageTable_one(one):
    print("getImageTable_one===========")
    print(one,dir(one),one.tag,one.text)
    rows=one.findall("Row")
    # for row in rows:
    #     print(row)
    # paras=[rows[0].text.replace("\n","")]
    # for one in rows[2:]:
    #     paras.append(one.text.replace("\n",""))
    print(len(rows))
    ele=rows[0].find("Cell").find("Text").text
    img=rows[1].find("Cell").find("Image").attrib["name"]
    paras=[]
    paras.append(ele)
    for i in (2,3,4,5):
        ele=rows[i].find("Cell").find("Text").text
        paras.append(ele)
    print(img,paras)
    return(img,paras)        
def output_curve(ws,hang):#outputsheet,pdf filename,0-n page
    ts=getimageTables()
    outputImages(ts,ws,hang)
def getdata(fname):
    data0=getdata_raw(fname)
    data=zl_data(data0)
    return data
def test_getdata():
    fname=os.path.join(getpath.getpath(),"..","data","037824-WZ","037824.xml")
    data=getdata(fname)
    # print(data)
    return data
def test1():
    fname=os.path.join(getpath.getpath(),"..","data","037824-WZ","037824.xml")
    data=getdata(fname)
    # getimageTables()
    print(data)
    # geti()
def geti():
    wb = openpyxl.Workbook()
    ws = wb.active
    output_curve(ws,1)
    wb.save("imags.xlsx")
if __name__=="__main__":
    test1()